package searcher;


import view.FetchDataMes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.swing.SwingWorker;

import model.Program;
import search.FileHandler;
import search.Parser;
import search.WebSpider;
import search.impl.FileHandlerImpl;

public final class Searcher extends SwingWorker<List<Program>,Integer>{

	public void getPrograms() {
		execute();	
	}
	
	
	@Override
	protected List<Program> doInBackground() throws Exception {
		// TODO Auto-generated method stub
	      try {
	            Class.forName("search.impl.Manager");
	      } catch (ClassNotFoundException e) {
	    	  System.out.println("Manager类不存在");
	       	}	
	      
	       List<WebSpider> webSpiders = SearchManager.getWebSpider();
	       
//	       List<Program> programs = new ArrayList<Program>();
	       List<Program> programs = new ArrayList<Program>();
	       
	       for (WebSpider webSpider : webSpiders) {
	        //   Parser parser = webSpider.getParser();
	           List<String> pages = webSpider.getHtmlFromWeb();	  
//	           //testscode -- 0
//	           System.out.println("pages: "+ pages.size());
//	           //testcode -- 1
	            for (String page : pages) {
//	            	// -- 0
//	            	System.out.println("page: " + page);
//	            	// -- 1 
	            	Parser parser = webSpider.getParser();
	            	parser.parse2Programs(programs,page); 
	            }
	       }	  
	       Integer chunks = programs.size();
	       
	       while(programs.size()<85) {
	    	   chunks = programs.size();
	    	   publish(chunks);
	       }
	   	   
	       FileHandler file = new FileHandlerImpl();
	       file.program2File(programs);
	       
	       //testcode -- 0
	//       System.out.println("programs: " + programs.size());
	       //testcode -- 1
	       return programs;
	}

	
	@Override
	protected void done() {
		// TODO Auto-generated method stub
		int size = 0;
		try {
			size = get().size();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		FetchDataMes.setProgressBar(size, true);
		FetchDataMes.setLabelAndPanel(true);
	}

	
	@Override
	protected void process(List<Integer> chunks) {
		// TODO Auto-generated method stub
		int size = chunks.get(chunks.size()-1);
		
//		System.err.println(size);
		
		FetchDataMes.setProgressBar(size, false);
	}
}

	

